# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :comment.py
# @Time      :2022/6/6 14:40
# @Author    :张志坤
from flask_restful import marshal, reqparse, Resource, Api
from flask import json, jsonify, request, Blueprint, g
from common.utils.login_utils import login_required
from common.model_fields.comment import comment_fields
from common.model_fields.user import user_fields
from models.user import *
from models import db

comment_bp = Blueprint("comment_bp", __name__)
api = Api(comment_bp)


class CommentList(Resource):
    @login_required
    def get(self, nid):
        """加载评论"""
        # 根据文章id 获取文章的   第一级评论
        comment1 = Comment.query.filter_by(article_id=nid, parent_id=None).all()
        if not comment1:
            return jsonify(msg="暂时还没有评论哦", code=400, data=[])

        # 通过第一级评论 获取第二级评论   也就是子评论
        comment_list = []
        for i in comment1:
            # 序列化每一个一级评论
            comment_ = marshal(i, comment_fields)
            # 获取所有二级评论
            comment2 = Comment.query.filter_by(parent_id=i.cmid).all()
            # 获取每一个一级评论的用户信息
            user1 = UserModel.query.filter_by(uid=i.user_id).first()

            comment2_list = []  # 用于存放二级评论
            for j in comment2:
                # 获取二级评论的用户信息
                user = UserModel.query.filter_by(uid=j.user_id).first()
                # 序列化每一个二级评论
                comment2_ = marshal(j, comment_fields)
                # 序列化每一个用户信息
                comment2_['user'] = marshal(user, user_fields)
                comment2_list.append(comment2_)
            # comment_['parent'] = comment2  # 二级评论信息赋值 parent
            comment_['parent'] = comment2_list
            comment_['user'] = marshal(user1, user_fields)  # 一级用户信息  赋值给一级评论  user里
            comment_list.append(comment_)
        return jsonify(data=comment_list)

    @login_required
    def post(self, nid):
        """
        :param nid:  文章id
        : uid  用户id
        :return:
        """
        uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument("content")
        parser.add_argument("parent_id")

        args = parser.parse_args()

        content = args['content']
        parent_id = args['parent_id']
        print("添加评论的数据", content)
        print("cmid>>>>>>>>>>>>>>>", parent_id)

        try:
            comment = Comment(user_id=uid, article_id=nid, parent_id=parent_id, content=content)
            db.session.add(comment)
        except Exception as e:
            print("添加评论报错", e)
            return jsonify(msg="评论失败", code=400)
        # 成功保存
        db.session.commit()
        return jsonify(msg="评论成功", code=200)


api.add_resource(CommentList, "/post_comment/<int:nid>")
